<script setup>
import { ref, onMounted, reactive } from "vue";
import _axios from '/src/utils/myAxios.js'
import { ElMessage, ElMessageBox } from 'element-plus'

let current = ref(1)
let size = ref(10)
let total = ref(0)

//搜索选项
let searchAccount = ref({
    nickname: undefined,
    username: undefined,
    status: undefined
})

//用户列表
let account = ref([])
let accountIds = ref([])

async function getAccount() {
    let resp = await _axios.post('/api/account/list', {
        current: current.value,
        size: size.value,
        nickname: searchAccount.value.nickname,
        username: searchAccount.value.username,
        status: searchAccount.value.status
    })
    if (resp.data.code === 200) {
        account.value = resp.data.data.rows
        total.value = resp.data.data.total
    } else {
        ElMessage({
            showClose: true,
            message: resp.data.message,
            type: 'error',
            appendTo: "#app",
        })
    }
}
onMounted(() => {
    getAccount()
})

//改变用户状态
function changeStatus(a) {
    const text = a.status === '0' ? '启用' : '停用'
    ElMessageBox.confirm(
        '确认要 ' + text + '' + a.nickname + ' 用户吗？',
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        return _axios.put('/api/account/updateStatus', {
            id: a.id,
            status: a.status
        })

    })
        .then(() => {
            ElMessage({
                showClose: true,
                message: text + "成功",
                type: 'success',
                appendTo: "#app",
            })
        })
        .catch(() => {
            a.status = a.status === '0' ? '1' : '0'
        })
}

//表单
let form = ref({
    id: undefined,
    nickname: undefined,
    username: undefined,
    password: undefined,
    sex: undefined,
    status: 0,
    roleId: undefined,
})

//重置表单
function resetForm() {
    form.value = {
        id: undefined,
        nickname: undefined,
        username: undefined,
        password: undefined,
        sex: undefined,
        status: 0,
        roleId: undefined,
    }
}

let formRule = reactive({ //文章表单规则
    nickname: [
        { required: true, message: '请输入昵称', trigger: 'blur' },
        { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
    ],
    username: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: "email", message: '请输入合法的电子邮件地址', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 30, message: '长度在 6 到 30 个字符', trigger: 'blur' }
    ]
})
let formRef = ref()

//弹框标题和是否可见
let dialog = ref({
    title: "",
    visible: false,
})

//角色列表
let roleOptions = ref([])

//获取角色列表
async function handleAdd() {
    resetForm()
    let resp = await _axios.get('/api/role/listAllRole')
    if (resp.data.code === 200) {
        roleOptions.value = resp.data.data
        dialog.value.title = "添加用户"
        dialog.value.visible = true
    }
}

//取消按钮
function cancel() {
    resetForm()
    dialog.value.visible = false
}

//添加和修改用户
function submitForm() {
    formRef.value.validate(async (valid) => {
        if (valid) {
            if (form.value.id == undefined) {
                let resp = await _axios.post('/api/account/addAccount', form.value)
                if (resp.data.code === 200) {
                    ElMessage({
                        showClose: true,
                        message: "添加用户成功",
                        type: 'success',
                        appendTo: "#app"
                    })
                    resetForm()
                    getAccount()
                    dialog.value.visible = false
                } else {
                    ElMessage({
                        showClose: true,
                        message: resp.data.message,
                        type: 'error',
                        appendTo: "#app"
                    })
                }
            } else {
                let resp = await _axios.put('/api/account/updateAccount', form.value)
                if (resp.data.code === 200) {
                    ElMessage({
                        showClose: true,
                        message: "修改用户成功",
                        type: 'success',
                        appendTo: "#app"
                    })
                    resetForm()
                    getAccount()
                    dialog.value.visible = false
                } else {
                    ElMessage({
                        showClose: true,
                        message: resp.data.message,
                        type: 'error',
                        appendTo: "#app"
                    })
                }
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'error',
                appendTo: "#app"
            })
        }
    }
    )
}

//删除用户
async function delAccount(id) {
    ElMessageBox.confirm(
        '确认要删除该用户吗？',
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        let resp = await _axios.delete(`/api/account/${id}`)
        return resp
    })
        .then((resp) => {
            if (resp.data.code === 200) {
                ElMessage({
                    showClose: true,
                    message: "删除成功",
                    type: 'success',
                    appendTo: "#app",
                })
                getAccount()
            }else{
                ElMessage({
                    showClose: true,
                    message: resp.data.message,
                    type: 'warning',
                    appendTo: "#app",
                })
            }
        })
}

//根据id查询用户
async function getAccountById(id) {
    let resp = await _axios.get(`/api/account/${id}`)
    let res = await _axios.get('/api/role/listAllRole')
    if (resp.data.code === 200 && res.data.code === 200) {
        form.value = resp.data.data
        roleOptions.value = res.data.data
        dialog.value.title = "修改用户"
        dialog.value.visible = true
    }
}

function changeAccountId(selection) {
    accountIds.value = selection.map(item => item.id)
}

// 批量删除用户
function delBatchAccount() {
    ElMessageBox.confirm(
        '确认要删除吗？',
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        let resp = await _axios.delete(`/api/account/delBatchAccount/${accountIds.value}`)
        return resp
    })
        .then((resp) => {
            if (resp.data.code === 200) {
                ElMessage({
                    showClose: true,
                    message: "删除成功",
                    type: 'success',
                    appendTo: "#app",
                })
                getAccount()
            }else{
                ElMessage({
                    showClose: true,
                    message: resp.data.message,
                    type: 'warning',
                    appendTo: "#app",
                })
            }
        })
}

//导出用户数据
function exportAccount() {
    ElMessageBox.confirm(
        '确认要导出所有用户数据吗？',
        '系统提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(async () => {
        let res = await _axios.get('/api/account/export', {
            responseType: 'blob'
        })
        if (!res.data) {
            return
        }
        var blob = new Blob([res.data])
        const contentDisposition = res.headers['content-disposition']
        var fileName = 'test.xlsx'
        if (contentDisposition) {
            fileName = window.decodeURI(res.headers['content-disposition'].split('=')[1], 'UTF-8')
        }
        var url = window.URL.createObjectURL(blob)
        var aLink = document.createElement('a')
        aLink.style.display = 'none'
        aLink.href = url
        aLink.setAttribute('download', fileName)
        document.body.appendChild(aLink)
        aLink.click()
        document.body.removeChild(aLink) // 下载完成移除元素
        window.URL.revokeObjectURL(url) // 释放掉blob对象
        return res
    })
        .then(() => {
            ElMessage({
                showClose: true,
                message: "数据导出成功",
                type: 'success',
                appendTo: "#app",
            })
            getMenu()
        })
}
</script>

<template>
    <div class="backMain">
        <el-form>
            <div class="backMain-search">
                <el-form-item prop="title" label="用户昵称">
                    <el-input v-model="searchAccount.nickname" placeholder="请输入用户昵称" />
                </el-form-item>
                <el-form-item prop="title" label="用户邮箱">
                    <el-input v-model="searchAccount.username" placeholder="请输入用户邮箱" />
                </el-form-item>
                <el-form-item label="用户状态">
                    <el-select v-model="searchAccount.status" placeholder="请选择用户状态">
                        <el-option label="正常" value=0 />
                        <el-option label="停用" value=1 />
                    </el-select>
                </el-form-item>
                <el-button type="primary" style="margin-left: 15px;" @click="getAccount()">搜索</el-button>
            </div>
            <div class="addAndDel">
                <el-button type="primary" plain size="small" @click="handleAdd">
                    <el-icon>
                        <iEpPlus />
                    </el-icon>&nbsp;
                    新增
                </el-button>
                <el-button type="warning" plain size="small" @click="delBatchAccount">
                    <el-icon>
                        <iEpDelete />
                    </el-icon>&nbsp;
                    删除
                </el-button>
                <el-button type="danger" plain size="small" @click="exportAccount()">
                    <el-icon>
                        <iEpDownload />
                    </el-icon>&nbsp;
                    导出
                </el-button>
            </div>
            <div class="user-content">
                <el-table :data="account" style="width: 100%;margin-top: 10px;" @selection-change="changeAccountId"
                    :cell-style="{ backgroundColor: 'var(--el-page-bg-color)' }">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="id" label="用户编号" align="center" />
                    <el-table-column prop="nickname" label="用户昵称" align="center" />
                    <el-table-column prop="username" label="用户邮箱" align="center" />
                    <el-table-column prop="sex" label="用户性别" align="center" />
                    <el-table-column prop="status" label="状态" align="center">
                        <template #default="scope">
                            <el-switch v-model="scope.row.status" active-value='0' inactive-value='1'
                                @change="changeStatus(scope.row)" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="createTime" label="创建时间" align="center" />
                    <el-table-column label="操作" align="center">
                        <template #default="scope">
                            <el-button text style="color: #409EFF" @click="getAccountById(scope.row.id)">编辑</el-button>
                            <el-button text style="color: #409EFF" @click="delAccount(scope.row.id)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-form>
        <div>
            <el-pagination v-model:current-page="current" v-model:page-size="size" :page-sizes="[10, 20, 30, 40]"
                size="small" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="getAccount"
                @current-change="getAccount" />
        </div>
        <!-- 添加和修改 -->
        <el-dialog v-model="dialog.visible" :title="dialog.title" width="600" align-center append-to-body
            style="background-color: #fff;font-weight: 600;">
            <el-form :inline="true" :model="form" :rules="formRule" ref="formRef">
                <el-form-item prop="nickname" label="用户昵称" size="large" style="width: 100%;">
                    <el-input v-model="form.nickname" placeholder="请输入用户昵称" />
                </el-form-item>
                <div style="display: flex;">
                    <el-form-item prop="username" label="用户邮箱" size="large">
                        <el-input v-model="form.username" placeholder="请输入用户邮箱" />
                    </el-form-item>
                    <el-form-item prop="password" label="用户密码" size="large" v-if="form.id == undefined">
                        <el-input type="password" show-password v-model="form.password" placeholder="请输入用户密码" />
                    </el-form-item>
                </div>
                <div style="display: flex;">
                    <el-form-item label="用户性别">
                        <el-select v-model="form.sex" placeholder="请选择用户性别" size="large" style="width: 185px;">
                            <el-option label="男" value="男" />
                            <el-option label="女" value="女" />
                            <el-option label="未知" value="未知" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="用户状态">
                        <el-radio-group v-model="form.status">
                            <el-radio :value=0>正常</el-radio>
                            <el-radio :value=1>停用</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>
                <el-form-item label="用户角色" size="large">
                    <el-select v-model="form.roleId" placeholder="请选择用户角色" style="width: 185px;">
                        <el-option v-for="role in roleOptions" :key="role.id" :label="role.roleName" :value="role.id" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="submitForm()">
                        确认
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<style scoped></style>